package com.android.demo_20220829.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.XXPermisionUtil;
import com.android.baselibrary.ui.BaseFragment;
import com.android.demo_20220829.R;
import com.android.demo_20220829.ui.activity.NavigationActivity;
import com.android.demo_20220829.ui.activity.SearchActivity;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.mapbox.api.directions.v5.models.RouteOptions;
import com.mapbox.geojson.Point;
import com.mapbox.maps.CameraOptions;
import com.mapbox.maps.MapView;
import com.mapbox.maps.MapboxMap;
import com.mapbox.maps.Style;
import com.mapbox.maps.plugin.Plugin;
import com.mapbox.maps.plugin.animation.CameraAnimationsPlugin;
import com.mapbox.maps.plugin.animation.MapAnimationOptions;
import com.mapbox.maps.plugin.annotation.AnnotationPlugin;
import com.mapbox.maps.plugin.attribution.AttributionPlugin;
import com.mapbox.maps.plugin.gestures.GesturesPlugin;
import com.mapbox.maps.plugin.gestures.OnMapClickListener;
import com.mapbox.maps.plugin.locationcomponent.LocationComponentPlugin;
import com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener;
import com.mapbox.maps.plugin.logo.LogoPlugin;
import com.mapbox.navigation.base.options.NavigationOptions;
import com.mapbox.navigation.base.route.NavigationRoute;
import com.mapbox.navigation.base.route.NavigationRouterCallback;
import com.mapbox.navigation.base.route.RouterFailure;
import com.mapbox.navigation.base.route.RouterOrigin;
import com.mapbox.navigation.core.MapboxNavigation;
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeMainFragment extends BaseFragment {

    @BindView(R.id.ll_head)
    LinearLayout ll_head;
    @BindView(R.id.mapView)
    MapView mMapView;


    MapboxMap mMapboxMap;
    Point currentPoint ;   //当前坐标

    private static final double DEFAULT_ZOOM_VALUE = 12.0;   // 初始地图缩放大小
    private static final double LOCATE_ZOOM_VALUE = 14.0;   // 定位后地图缩放大小
    private AnnotationPlugin mAnnotationPlugin;         // 地图注释组件
    private LocationComponentPlugin mLocationPlugin;    // 位置定位组件
    private GesturesPlugin mGesturesPlugin;     // 手势组件
    private CameraAnimationsPlugin mCameraAnimationsPlugin;     // 相机动画组件

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_nav;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).titleBar(ll_head).init();
    }

    @Override
    protected void initData() {
        mAnnotationPlugin = mMapView.getPlugin(Plugin.MAPBOX_ANNOTATION_PLUGIN_ID);
        mLocationPlugin = mMapView.getPlugin(Plugin.MAPBOX_LOCATION_COMPONENT_PLUGIN_ID);
        mCameraAnimationsPlugin = mMapView.getPlugin(Plugin.MAPBOX_CAMERA_PLUGIN_ID);


        mMapboxMap = mMapView.getMapboxMap();
        mMapboxMap.loadStyleUri(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
            @Override
            public void onStyleLoaded(@NonNull Style style) {
                List<String> arr = new ArrayList<>();
                arr.add(Permission.ACCESS_COARSE_LOCATION);
                arr.add(Permission.ACCESS_FINE_LOCATION);
                arr.add(Permission.ACCESS_BACKGROUND_LOCATION);

                //地图加载完
                XXPermisionUtil.requstPermision(mContext, new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        // 设置脉冲显示
                        mLocationPlugin.updateSettings(locationComponentSettings -> {
                            locationComponentSettings.setEnabled(true);
                            locationComponentSettings.setPulsingEnabled(true);  // 脉冲效果
                            return null;
                        });
                        mLocationPlugin.addOnIndicatorPositionChangedListener(new OnIndicatorPositionChangedListener() {
                            @Override
                            public void onIndicatorPositionChanged(@NonNull Point point) {
                                currentPoint = point;
                                // 相机跟随
                                moveCameraTo(point, LOCATE_ZOOM_VALUE, 0);
                                if (mGesturesPlugin != null) {
                                    mGesturesPlugin.setFocalPoint(mMapboxMap.pixelForCoordinate(point));
                                }
                            }
                        });
                    }
                }, arr.toArray(new String[arr.size()]));
            }
        });

        //隐藏logo
        LogoPlugin logoPlugin = mMapView.getPlugin(Plugin.MAPBOX_LOGO_PLUGIN_ID);
        if (logoPlugin != null) {
            logoPlugin.setEnabled(false);
        }
        //隐藏感叹号
        AttributionPlugin attributionPlugin = mMapView.getPlugin(Plugin.MAPBOX_ATTRIBUTION_PLUGIN_ID);
        if (attributionPlugin != null) {
            attributionPlugin.setEnabled(false);
        }

        //手势插件
        mGesturesPlugin = mMapView.getPlugin(Plugin.MAPBOX_GESTURES_PLUGIN_ID);
        mGesturesPlugin.addOnMapClickListener(new OnMapClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public boolean onMapClick(@NonNull Point point) {
                //长按
                if (!MapboxNavigationApp.isSetup()) {
//                    String token = getString(R.string.mapbox_access_token);
//                    MapboxNavigationApp app =  MapboxNavigationApp.setup(new NavigationOptions.Builder(mContext).accessToken(token).build());
//                    getRouter(app ,point);

                    StartActivity(NavigationActivity.class);
                }

                return false;
            }
        });
    }

    //获取路线
    private void getRouter(MapboxNavigationApp app,Point endPoint) {
        List<Point> points = new ArrayList<>();
        points.add(currentPoint);
        points.add(endPoint);
        RouteOptions routeOptions = RouteOptions.builder()
                .coordinatesList(points)
                .alternatives(false)
                .build();
        app.current().requestRoutes(routeOptions, new NavigationRouterCallback() {
            @Override
            public void onRoutesReady(@NonNull List<NavigationRoute> list, @NonNull RouterOrigin routerOrigin) {
                Log.i("list.size():"+ list.size());

            }

            @Override
            public void onFailure(@NonNull List<RouterFailure> list, @NonNull RouteOptions routeOptions) {

            }

            @Override
            public void onCanceled(@NonNull RouteOptions routeOptions, @NonNull RouterOrigin routerOrigin) {

            }
        });
    }


    /**
     * 将摄像头移动到指定位置
     *
     * @param point    目标坐标
     * @param zoom     缩放比例
     * @param duration 滑动总时间 0为无动画
     */
    public void moveCameraTo(Point point, double zoom, int duration) {
        if (mMapView == null) {
            return;
        }
        if (duration != 0 && mCameraAnimationsPlugin != null) {
            mCameraAnimationsPlugin.flyTo(new CameraOptions.Builder()
                            .center(point)
                            .zoom(zoom)
                            .build(),
                    new MapAnimationOptions.Builder().duration(duration).build());
        } else {
            mMapboxMap.setCamera(new CameraOptions.Builder()
                    .center(point)
                    .zoom(zoom)
                    .build());
        }
    }

    private void getRoute(Point origin, Point destination) {

        RouteOptions.builder().build();
    }


    @OnClick({R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
//                StartActivity(SearchActivity.class);
                StartActivity(NavigationActivity.class);
                break;
        }
    }


}
